package butines.core.game.graph;

import java.util.ArrayList;
import java.util.Iterator;


public class Node<EdgeType extends Edge<?>> implements Iterable<EdgeType> {

	private int id;
	private ArrayList<EdgeType> edges;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public ArrayList<EdgeType> getEdges() {
		if (edges == null) {
			edges = new ArrayList<EdgeType>();
		}
		return edges;
	}

	public EdgeType getEdge(Node<?> to) {
		for (EdgeType edge: this) {
			if (edge.getTo() == to) {
				return edge;
			}
		}
		return null;
	}

	public void addEdge(EdgeType edge) {
		if (edge == null) {
			throw new IllegalArgumentException("edge is null");
		}
		if (edge.getFrom() != this) {
			throw new IllegalArgumentException("edge from is invalid. Node: " + this + ", edge: " + edge);
		}
		if (getEdge(edge.getTo()) != null) {
			throw new IllegalArgumentException("already exists edge to node. Node: " + this + ", edge: " + edge);
		}
		getEdges().add(edge);
	}
	
	public void removeEdge(Node<?> to) {
		if (to == null) {
			throw new IllegalArgumentException("to is null");
		}
		EdgeType edge = getEdge(to);
		if (edge == null) {
			throw new IllegalArgumentException("not exists edge to node");	
		}
		getEdges().remove(edge);
	}
	
	public void removeEdges() {
		while (getNumEdges() > 0) {
			getEdges().get(0).remove();
		}
	}
	
	public Iterator<EdgeType> iterator() {
		return getEdges().iterator();
	}
	
	public int getNumEdges() {
		return getEdges().size();
	}
	
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("ID: ").append(id).append(" >");
		
		for (EdgeType edge: this) {
			sb.append(' ');
			sb.append(edge.getTo().getId());
		}
		return sb.toString();
	}
	
}
